package com.tundriki.pref;

import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.view.MotionEvent;

public class GameClient {
	private TextureBundle tex;
	
	public static int NONE=-1;
	
	private FloatBuffer deskVert;
	private int deskTex;
	
	CardHolder north,
			east,
			west,
			south,
			center;
	
	
	Card deck[] = new Card[53];
	final static int playingCards[] =
			{45,46,47,48,49,50,51,39, // spades
			  6, 7, 8, 9,10,11,12, 0, // clubs
			 19,20,21,22,23,24,25,13, // diamonds
			 32,33,34,35,36,37,38,26};//hearts
	
	public GameClient(TextureBundle tex) {
		this.tex = tex;
		
		deskTex = this.tex.texByName("Desk");
		deskVert = tex.bufferFromResources(R.array.deskShape, 3);
		
		for(int i=0;i<deck.length;i++)
			deck[i] = new Card(this.tex, tex.cardNames[i]);
		
		deck[52].hideFace();
		
		north = new CardHolder(tex.arrayFromResources(R.array.northPlaces, 3));
		east =  new CardHolder(tex.arrayFromResources(R.array.eastPlaces, 3));
		south =  new CardHolder(tex.arrayFromResources(R.array.southPlaces, 3));
		west =  new CardHolder(tex.arrayFromResources(R.array.westPlaces, 3));
		center  =  new CardHolder(tex.arrayFromResources(R.array.deskPlaces, 3));
		
		setRandom();
	}
	
	private void setRandom () {
		int[] crd =  playingCards.clone();
		int len = crd.length;
				
		while(len>0) {
			int j = (int)(Math.random()*len);
			
			if (len>22)
				south.addCard(deck[crd[j]]);
			else if (len>12)
				west.addCard(deck[crd[j]]);
			else if (len>2)
				east.addCard(deck[crd[j]]);
			else
				center.addCard(deck[crd[j]]);
			len --;
			for(int i=j;i<len;i++)
				crd[i] = crd[i+1];
		}
		north.sortCards();
		south.sortCards();
		west.sortCards();
		east.sortCards();

	}
	
	private void drawDesk(GL10 gl) {
		gl.glColor4f(0.1f, 0.9f, 0.1f, 0f);
		deskVert.position(0);
		tex.stdTexMap.position(0);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, deskTex);
	    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, deskVert);
	    gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, tex.stdTexMap);
	    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

	}
	
	public void draw(GL10 gl) {
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
	    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

	    gl.glFrontFace(GL10.GL_CW);

		drawDesk(gl);
		
		north.draw(gl);
		east.draw(gl);
		west.draw(gl);
		center.draw(gl);
		south.draw(gl);
		
	    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
	    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

	}
	
	public void onActionEvent(float[][] coord, int evt) {
		if (evt==MotionEvent.ACTION_UP) {
			Card c=south.cardFromScreenEvent(coord);
			if (c!=null)
				c.rotateBy(180f);
		}
		
		
	}

}
